package com.ph.shopping.facade.order.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import cm.ph.shopping.facade.order.entity.PhOrderAddress;
import cm.ph.shopping.facade.order.entity.PhOrderOnline;
import cm.ph.shopping.facade.order.entity.PhOrderUnline;
import cm.ph.shopping.facade.order.request.PhOrderOnlineRequest;
import cm.ph.shopping.facade.order.request.UserRequest;
import cm.ph.shopping.facade.order.service.IOrderService;
import cm.ph.shopping.facade.order.vo.ProductNumAndIdVo;
import cm.ph.shopping.facade.order.vo.ProductVo;
import cm.ph.shopping.facade.order.vo.QueryOnLineOrderDetailVo;
import cm.ph.shopping.facade.order.vo.QueryOnLineOrderVo;
import cm.ph.shopping.facade.order.vo.QueryOrderAddressVo;
import cm.ph.shopping.facade.order.vo.QueryUserAddressVo;
import cm.ph.shopping.facade.order.vo.QueryWebOnLineOrderDetailVo;
import cm.ph.shopping.facade.order.vo.QueryWebOnLineOrderVo;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ph.shopping.common.core.base.BaseService;
import com.ph.shopping.common.core.customenum.ResultEnum;
import com.ph.shopping.common.util.com.order.Constants;
import com.ph.shopping.common.util.com.order.CreateOrderUtil;
import com.ph.shopping.common.util.com.order.OrderBizCode;
import com.ph.shopping.common.util.container.ParamVerifyUtil;
import com.ph.shopping.common.util.page.PageBean;
import com.ph.shopping.common.util.result.Result;
import com.ph.shopping.common.util.transform.MoneyTransUtil;
import com.ph.shopping.facade.mapper.IOrderAddressMapper;
import com.ph.shopping.facade.mapper.IOrderOnlineMapper;
import com.ph.shopping.facade.mapper.IOrderUnlineMapper;
import com.ph.shopping.facade.mapper.IPurchaseListMapper;

@Component
@Service(version = "1.0.0")
public class OrderServiceImpl extends BaseService implements IOrderService {

	@Autowired
	private IOrderOnlineMapper onlineMapper;

	@Autowired
	private IOrderUnlineMapper unlineMapper;

	@Autowired
	private IOrderAddressMapper addressMapper;

	@Autowired
	private IPurchaseListMapper iPurchaseListMapper;

	/**
	 * 创建线上订单
	 */
	@Override
	public Result insertPhOrderOnline(PhOrderOnlineRequest request) throws Exception {
		PhOrderOnline orderOnline = new PhOrderOnline();
		long productId = request.getProductId();
		int buyNum = request.getNum();
		ProductVo productVo = onlineMapper.getProduct(productId);
		productVo.setFreight(MoneyTransUtil.transDivisDouble(productVo.getFreight1()));
		productVo.setRetailPrice(MoneyTransUtil.transDivisDouble(productVo.getRetailPrice1()));

		if (buyNum > productVo.getProductCount()) {
			return getResult(ResultEnum.NO_PRODUCT);
		}

		double postage = 0.0D;
		if (productVo.getNumberOfPackages() <= buyNum) {
			orderOnline.setPostage(MoneyTransUtil.transMultiDouble(postage));
		} else {
			postage = productVo.getFreight() * buyNum;
			orderOnline.setPostage(MoneyTransUtil.transMultiDouble(postage));
		}
		// 商品总价
		double productMoney = productVo.getRetailPrice() * buyNum;
		// 订单金额
		double payMoney = postage + productMoney;

		if (request.getPayMoney() != payMoney) {
			return getResult(ResultEnum.MONEY_EXCEPTION);
		}

		orderOnline.setOrderNo(CreateOrderUtil.createOrderCode(OrderBizCode.MEMBER_ORDER));
		orderOnline.setPrice(productVo.getRetailPrice1());
		orderOnline.setPayMoney(MoneyTransUtil.transMultiDouble(payMoney));

		orderOnline.setAddrDetail(request.getAddrDetail());
		orderOnline.setAddrId(request.getAddrId());
		orderOnline.setContact(request.getContact());
		orderOnline.setDeliveryDate(new Date());
		orderOnline.setMemberId(request.getMemberId());
		orderOnline.setNum(buyNum);
		orderOnline.setProductId(productId);
		orderOnline.setTelPhone(request.getTelPhone());
		orderOnline.setDeliveryType(request.getDeliveryType());
		orderOnline.setPickPointId(request.getPickPointId());
		orderOnline.setStatus(Constants.WAIT_PAY);

		int ret = onlineMapper.insertSelective(orderOnline);
		if (ret == 1) {
			iPurchaseListMapper.updateProductNum(orderOnline.getNum(), orderOnline.getProductId());
			return getResult(ResultEnum.SUCCESS);
		} else {
			throw new Exception("创建线上订单异常!");
		}
	}

	/**
	 * 更新订单状态
	 */
	@Override
	public int updatePhOrderOnline(String orderNo, int status) throws Exception {
		if (status == 5 || status == 6) {
			// 返回商品数量
			ProductNumAndIdVo numAndIdVo = onlineMapper.getProductNum(orderNo);

			iPurchaseListMapper.updateAddProductNum(numAndIdVo.getNum(), numAndIdVo.getProductId());
		}
		return onlineMapper.updateOnLineOrder(orderNo, status);
	}

	/**
	 * 创建线下订单(暂时不用)
	 */
	@Override
	public int insertPhOrderUnline(PhOrderUnline orderUnline) throws Exception {
		return unlineMapper.insert(orderUnline);
	}

	/**
	 * 查询后台订单列表
	 */
	@Override
	public Result findOnlineOrders(UserRequest userRequest, PageBean pageBean) throws Exception {
		PageHelper.startPage(pageBean.getPageNum(), pageBean.getPageSize(), "deliverydate desc");
		List<QueryOnLineOrderVo> list = onlineMapper.listOnlineOrders(userRequest.getAgentId(),
				userRequest.getSupplierId(), userRequest.getOrderNo(), userRequest.getRoleCode());
		if (ParamVerifyUtil.objIsNotNull(list)) {
			for (QueryOnLineOrderVo orderVo : list) {
				orderVo.setPrice(MoneyTransUtil.transDivisDouble(orderVo.getPrice1()));
				orderVo.setPayMoney(MoneyTransUtil.transDivisDouble(orderVo.getPayMoney1()));
				orderVo.setPostage(MoneyTransUtil.transDivisDouble(orderVo.getPostage1()));
			}
		}

		PageInfo<QueryOnLineOrderVo> page = new PageInfo<QueryOnLineOrderVo>(list);
		return getResult(ResultEnum.SUCCESS, page.getList(), page.getTotal());
	}

	/**
	 * 新增收货地址
	 */
	@Override
	public Result insertOrderAddress(PhOrderAddress orderAddress) throws Exception {
		int count = addressMapper.countOrderAddr(orderAddress.getMemberId());
		if (count > 20) {
			return getResult(ResultEnum.ADD_ORDER_ADDRESS_FULL);
		}

		if (count > 0) {
			if (orderAddress.getIsdefault() == Constants.ISDEFAULT) {
				// 更新已有默认地址为非默认
				if (addressMapper.updateOrderAddrNotDefault(orderAddress.getMemberId(),
						orderAddress.getId(), Constants.NOTDEFAULT) < 1) {
					return getResult(ResultEnum.CANCEL_ORDER_ADDRESS_DEFAULT_FAIL);
				}
			}
		}

		// 如果是第一个新增的地址，设为默认地址
		if (count == 0) {
			orderAddress.setIsdefault(Constants.ISDEFAULT);
		}

		orderAddress.setCreateTime(new Date());

		if (addressMapper.insert(orderAddress) < 1) {
			return getResult(ResultEnum.ADD_ORDER_ADDRESS_FAIL);
		}

		return getResult(ResultEnum.SUCCESS);
	}

	/**
	 * 删除收货地址
	 */
	@Transactional
	@Override
	public Result deleteOrderAddress(long id) throws Exception {
		if (addressMapper.deleteByPrimaryKey(id) < 1) {
			return getResult(ResultEnum.DEL_ORDER_ADDRESS_FAIL);
		}

		return getResult(ResultEnum.SUCCESS);
	}

	/**
	 * 修改收货地址
	 */
	@Transactional
	@Override
	public Result updateOrderAddress(PhOrderAddress orderAddress) throws Exception {
		if (addressMapper.updateByPrimaryKeySelective(orderAddress) < 1) {
			return getResult(ResultEnum.UPD_ORDER_ADDRESS_FAIL);
		}
		return getResult(ResultEnum.SUCCESS);
	}

	/**
	 * 查询收货地址列表
	 */
	@Override
	public Result queryOrderAddress(long memberId) {
		List<QueryOrderAddressVo> list = addressMapper.selectByIdAndMemberId(memberId);
		for (QueryOrderAddressVo addressVo : list) {
			addressVo.setAddress(addressVo.getProvince() + addressVo.getCity()
					+ addressVo.getArea() + addressVo.getAddress());
		}
		return getResult(ResultEnum.SUCCESS, list);
	}

	/**
	 * 
	 * @Title: queryAddressDetail
	 * @Description: 查询收货地址详情
	 * @author zhengpeng
	 * @date 2017年3月17日 上午11:39:42
	 * @param addressId
	 * @return
	 */
	@Override
	public Result queryAddressDetail(long addressId) {
		return getResult(ResultEnum.SUCCESS, addressMapper.selectByPrimaryKey(addressId));
	}

	/**
	 * 设置默认地址
	 */
	@Transactional
	@Override
	public Result updateOrderAddrDef(long memberId, long orderAddrId) throws Exception {

		if (addressMapper.updateOrderAddrNotDefault(memberId, orderAddrId, Constants.NOTDEFAULT) < 1) {
			return getResult(ResultEnum.CANCEL_ORDER_ADDRESS_DEFAULT_FAIL);
		}

		if (addressMapper.updateOrderAddrDefault(memberId, orderAddrId, Constants.ISDEFAULT) < 1) {
			return getResult(ResultEnum.UPD_ORDER_ADDRESS_DEFAULT_FAIL);
		}

		return getResult(ResultEnum.SUCCESS);
	}

	/**
	 * 
	 * Title: queryWebOnLineOrders Description:查询商城订单列表
	 * 
	 * @author WQiang
	 * @date 2017年3月28日 下午4:30:21
	 * @param memberId
	 * @param status
	 * @param pageNum
	 * @param pageSize
	 * @return
	 * @see cm.ph.shopping.facade.order.service.IOrderService#queryWebOnLineOrders(long,
	 *      int, int, int)
	 */
	@Override
	public Result queryWebOnLineOrders(long memberId, int status, int pageNum, int pageSize) {
		PageHelper.startPage(pageNum, pageSize);
		List<QueryWebOnLineOrderVo> list = onlineMapper.listWebOnLineOrders(memberId, status);
		for (QueryWebOnLineOrderVo orderVo : list) {
			orderVo.setPrice(MoneyTransUtil.transDivisDouble(orderVo.getPrice1()));
			orderVo.setPayMoney(MoneyTransUtil.transDivisDouble(orderVo.getPayMoney1()));
		}
		PageInfo<QueryWebOnLineOrderVo> page = new PageInfo<QueryWebOnLineOrderVo>(list);
		return getResult(ResultEnum.SUCCESS, page.getList(), page.getTotal());
	}

	/**
	 * 
	 * Title: getWebOnLineOrderDetail Description:获取会员订单详情
	 * 
	 * @author WQiang
	 * @date 2017年3月28日 下午6:34:20
	 * @param orderId
	 * @return
	 * @see cm.ph.shopping.facade.order.service.IOrderService#getWebOnLineOrderDetail(long)
	 */
	@Override
	public Result getWebOnLineOrderDetail(long orderId, int deliveryType) throws Exception {
		try {
			QueryWebOnLineOrderDetailVo orderDetal = onlineMapper.getWebOnLineOrderDetail(orderId,
					deliveryType);
			orderDetal.setAddressDetail(orderDetal.getProvince() + orderDetal.getCity()
					+ orderDetal.getArea() + orderDetal.getAddress());
			orderDetal.setPrice(MoneyTransUtil.transDivisDouble(orderDetal.getPrice1()));
			orderDetal.setPayMoney(MoneyTransUtil.transDivisDouble(orderDetal.getPayMoney1()));
			orderDetal.setPostage(MoneyTransUtil.transDivisDouble(orderDetal.getPostage1()));
			return getResult(ResultEnum.SUCCESS, orderDetal);

		} catch (Exception e) {
			logger.error("获取详情失败", e.getMessage());
			return getResult(ResultEnum.INTERNAL_SERVER_ERROR);
		}
	}

	public Result getWebOnLineOrderDetail(long orderId) {
		return null;
	}

	/**
	 * 
	 * Title: querySupplyerName Description:获取供应商名称
	 * 
	 * @author WQiang
	 * @date 2017年3月29日 下午2:49:30
	 * @param productId
	 * @return
	 * @see cm.ph.shopping.facade.order.service.IOrderService#querySupplyerName(long)
	 */
	@Override
	public Result querySupplyerName(long productId) {

		return getResult(ResultEnum.SUCCESS, onlineMapper.getSupplyerName(productId));
	}

	/**
	 * 
	 * Title: getOrderDetail Description:获取订单详情
	 * 
	 * @author WQiang
	 * @date 2017年3月31日 上午10:20:01
	 * @param id
	 * @return
	 * @see cm.ph.shopping.facade.order.service.IOrderService#getOrderDetail(long)
	 */
	@Override
	public QueryOnLineOrderDetailVo getOrderDetail(long id) {

		return onlineMapper.getOnLineOrderDetail(id);
	}

	@Override
	public Result getUserAddress(long userId) {
		List<QueryUserAddressVo> list = onlineMapper.getSendAddress(userId);
		return getResult(ResultEnum.SUCCESS, list);
	}

	@Override
	public Result updateOrderToSend(int status, String logisticName, String logisticNo, long orderId) {
		if (onlineMapper.updateOrderToSend(status, logisticName, logisticNo, orderId) == 1) {
			return getResult(ResultEnum.SUCCESS);
		} else {
			return getResult(ResultEnum.FAIL);
		}
	}

}
